<template>
  <el-row :gutter="24" :style="{ paddingRight: collapseTree ? 'var(--mian-left-width)' : '0' }">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-[calc(100vh-var(--heard-height))]" :isTree="true" v-if="!collapseTree">
        <DeptTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="collapseTree ? 24 : 20" :xs="24">
      <ContentWrap ref="form">
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="用户账号" prop="username">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入用户账号"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入手机号码"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="身份证号" prop="idNumber">
            <el-input
              v-model="queryParams.idNumber"
              placeholder="请输入身份证号"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>

          <el-form-item label="用户类型" prop="userType">
            <el-select
              v-model="queryParams.userType"
              placeholder="请选择用户类型"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="用户状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" />重置</el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['system:user:create']"
            >
              <Icon icon="ep:plus" /> 新增
            </el-button>
            <el-button
              type="primary"
              plain
              @click="openTeacherUserCreateForm"
              v-hasPermi="['system:user:create']"
            >
              <Icon icon="ep:plus" /> 新增老师用户
            </el-button>
            <el-button
              type="warning"
              plain
              @click="handleImport"
              v-hasPermi="['system:user:import']"
            >
              <Icon icon="ep:upload" /> 导入
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['system:user:export']"
            >
              <Icon icon="ep:download" />导出
            </el-button>
            <el-button
              type="primary"
              plain
              @click="openTeacherUserGenerateForm()"
              v-hasPermi="['system:user:create']"
            >
              <Icon icon="ep:plus" /> 集体新增
            </el-button>
            <el-button type="danger" @click="handleDeleteMulti" v-hasPermi="['system:user:delete']">
              <Icon icon="ep:delete" class="mr-5px" />
              批量删除
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <ContentWrap :setPadding="false">
        <el-table
          v-loading="loading"
          :data="list"
          @selection-change="selectionChange"
          stripe
          :max-height="tableHeight"
        >
          <el-table-column type="selection" width="55" />
          <!-- <el-table-column label="用户编号" key="id" prop="id" /> -->
          <el-table-column label="用户账号" prop="username" show-overflow-tooltip />
          <el-table-column label="用户昵称" prop="nickname" show-overflow-tooltip />
          <el-table-column label="部门" key="deptName" prop="dept.name" show-overflow-tooltip />
          <el-table-column label="用户类型 " prop="userType">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SYSTEM_USER_TYPE" :value="scope.row.userType" />
            </template>
          </el-table-column>
          <el-table-column label="手机号码" prop="mobile" width="120" show-overflow-tooltip />
          <el-table-column label="身份证号" prop="idNumber" show-overflow-tooltip />
          <el-table-column label="状态" key="status">
            <!-- <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="0"
                :inactive-value="1"
                @change="handleStatusChange(scope.row)"
              />
            </template> -->
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            prop="createTime"
            :formatter="dateFormatter"
            width="180"
            show-overflow-tooltip
          />
          <el-table-column label="操作" fixed="right" width="180">
            <template #default="scope">
              <div class="flex justify-center items-center">
                <el-button type="primary" link v-hasPermi="['member:user:update']">
                  状态
                  <el-switch
                    style="margin-left: 5px"
                    v-model="scope.row.status"
                    :active-value="0"
                    :inactive-value="1"
                    @change="handleStatusChange(scope.row)"
                  />
                </el-button>
                <!-- <el-button
                  type="primary"
                  link
                  @click="openForm('update', scope.row.id)"
                  v-hasPermi="['system:user:update']"
                >
                  <Icon icon="ep:edit" />修改
                </el-button> -->
                <el-dropdown
                  @command="(command) => handleCommand(command, scope.row)"
                  v-hasPermi="[
                    'system:user:delete',
                    'system:user:update',
                    'system:user:update-password',
                    'system:permission:assign-user-role',
                    'system:user:unbind-teacher',
                    'system:user:bind-teacher'
                  ]"
                >
                  <el-button class="ml-2" type="primary" link
                    ><Icon icon="ep:d-arrow-right" /> 更多</el-button
                  >
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        command="handleUpdate"
                        v-if="checkPermi(['system:user:update'])"
                      >
                        <Icon icon="ep:edit" />修改
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="handleDelete"
                        v-if="checkPermi(['system:user:delete'])"
                      >
                        <Icon icon="ep:delete" />删除
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="handleResetPwd"
                        v-if="checkPermi(['system:user:update-password'])"
                      >
                        <Icon icon="ep:key" />重置密码
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="handleRole"
                        v-if="checkPermi(['system:permission:assign-user-role'])"
                      >
                        <Icon icon="ep:circle-check" />分配角色
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="handleUnbindTeacher"
                        v-if="checkPermi(['system:user:unbind-teacher']) && scope.row.bindingId"
                      >
                        <Icon icon="ep:key" />解绑老师
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="handleBindTeacher"
                        v-if="checkPermi(['system:user:bind-teacher']) && !scope.row.bindingId"
                      >
                        <Icon icon="ep:key" />绑定老师
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 添加或修改用户对话框 -->
  <UserForm ref="formRef" @success="getList" />
  <!-- 添加或修改用户对话框 -->
  <TeacherUserGenerateForm ref="teacherUserGenerateFormRef" @success="getList" />
  <!-- 添加老师用户对话框 -->
  <TeacherUserCreateForm ref="teacherUserCreateFormRef" @success="getList" />
  <!-- 绑定老师用户对话框 -->
  <TeacherUserBindForm ref="teacherUserBindFormRef" @success="getList" />
  <!-- 用户导入对话框 -->
  <UserImportForm ref="importFormRef" @success="getList" />
  <!-- 分配角色 -->
  <UserAssignRoleForm ref="assignRoleFormRef" @success="getList" />
</template>
<script setup lang="ts" name="SystemUser">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { checkPermi } from '@/utils/permission'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CommonStatusEnum } from '@/utils/constants'
import * as UserApi from '@/api/system/user'
import UserForm from './UserForm.vue'
import TeacherUserGenerateForm from './TeacherUserGenerateForm.vue'
import UserImportForm from './UserImportForm.vue'
import UserAssignRoleForm from './UserAssignRoleForm.vue'
import DeptTree from '@/components/DeptTree.vue'
import TeacherUserCreateForm from './TeacherUserCreateForm.vue'
import TeacherUserBindForm from './TeacherUserBindForm.vue'
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const collapseTree = computed(() => appStore.getCollapseTree)

const form = ref(null)
const { width, height } = useElementSize(form)
const tableHeight = useWindowSize(78 + 76, height)

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  username: undefined,
  mobile: undefined,
  status: undefined,
  deptId: undefined,
  createTime: [],
  idNumber: undefined
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.deptId = undefined
  handleQuery()
}

/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 打开生成老师框 */
const teacherUserGenerateFormRef = ref()
const openTeacherUserGenerateForm = () => {
  teacherUserGenerateFormRef.value.open()
}

/** 打开创建老师框 */
const teacherUserCreateFormRef = ref()
const openTeacherUserCreateForm = () => {
  teacherUserCreateFormRef.value.open()
}

/** 打开绑定老师框 */
const teacherUserBindFormRef = ref()
const openTeacherUserBindForm = (id: number) => {
  teacherUserBindFormRef.value.open(id)
}

/** 用户导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 修改用户状态 */
const handleStatusChange = async (row: UserApi.UserVO) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
    await message.confirm('确认要"' + text + '""' + row.username + '"用户吗?')
    // 发起修改状态
    await UserApi.updateUserStatus(row.id, row.status)
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status =
      row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}

/** 导出按钮操作 */
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await UserApi.exportUser(queryParams)
    download.excel(data, '用户数据.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 解绑老师 */
const unbindTeacher = async (id: number) => {
  try {
    // 解绑的二次确认
    const result = await message.confirm('请确认是否解绑老师?', '解绑老师')
    if (result) {
      await UserApi.unbindTeacher(id)
      await getList()
    }
  } catch {}
}

const listOfIds = ref([]) //选中的设备

// 选中设备
const selectionChange = (val: any) => {
  listOfIds.value = val.map((item: any) => item.id)
}

// 批量删除操作
const handleDeleteMulti = async () => {
  if (listOfIds.value.length > 0) {
    try {
      // 批量删除的二次确认
      await message.delConfirm()
      // 发起批量删除
      await UserApi.batchDeleteUser(listOfIds.value)
      message.success(t('common.delSuccess'))
      // 刷新列表
      await getList()
    } catch {}
  } else {
    message.warning(t('请选择要删除的用户!'))
  }
}

/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleUpdate':
      handleUpdate(row.id)
      break
    case 'handleDelete':
      handleDelete(row.id)
      break
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    case 'handleRole':
      handleRole(row)
      break
    case 'handleUnbindTeacher':
      unbindTeacher(row.id)
      break
    case 'handleBindTeacher':
      openTeacherUserBindForm(row.id)
      break
    default:
      break
  }
}

/** 编辑按钮操作 */
const handleUpdate = async (id: number) => {
  openForm('update', id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserApi.deleteUser(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 重置密码 */
const handleResetPwd = async (row: UserApi.UserVO) => {
  try {
    ElMessageBox.prompt('请输入"' + row.username + '"的新密码', t('common.reminder'), {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      customClass: 'keep-default',
      inputValidator: (value) => {
        if (!value || !value.trim()) {
          return '密码不能为空'
        }
        return true
      },
      beforeClose: async (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          try {
            console.log(instance)

            await UserApi.resetUserPwd(row.id, instance.inputValue)
            message.success('修改成功，新密码是：' + instance.inputValue)
            done() // 操作成功，关闭弹窗
          } catch (error) {
            instance.confirmButtonLoading = false
            // message.error('密码重置失败')
          }
        } else {
          done()
        }
      }
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '取消重置'
      })
    })
  } catch {}
}

/** 分配角色 */
const assignRoleFormRef = ref()
const handleRole = (row: UserApi.UserVO) => {
  assignRoleFormRef.value.open(row)
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>
